package com.lvyq.myjob;

import com.lvyq.common.pasture.PastureGrowUpType;
import com.lvyq.model.farm.MyPlant;
import com.lvyq.model.pasture.MyPasture;
import com.lvyq.model.pasture.PastureFeeding;
import com.lvyq.model.user.User;
import com.lvyq.repository.UserRepository;
import com.lvyq.repository.pasture.MyPastureRepository;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: weg
 * @description:
 * @author: lvyq
 * @create: 2023-03-19 22:18
 **/
@Component
public class MyJob {

    @Resource
    private UserRepository userRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MyPastureRepository myPastureRepository;

    /** 
    * @Description: 签到任务重置- 每日凌晨重置
    * @params:  * @param 
    * @return:   秒 分 时 日 月 周
    * @Author: lvyq
    * @Date: 2023/3/19 22:20
    */
    @Scheduled(cron = "0 0 0 * * ?")
    public void JianDaoJob(){
        //修改签到状态
        Query query = new Query();
        Update update = new Update();
        update.set("isSignIn",false);
        mongoTemplate.updateFirst(query,update,User.class);
    }

    /** 
    * @Description: 作物状态修改
    * @params:  * @param 
    * @return: 
    * @Author: lvyq
    * @Date: 2023/4/8 15:57
    */
    @Scheduled(fixedRate = 1000*5)
    public void MyPlantChange(){
        Query query = new Query().addCriteria(Criteria.where("state").is(0));
        List<MyPlant> myPlants = mongoTemplate.find(query,MyPlant.class);
        for (MyPlant myPlant:myPlants){
            if (new Date().getTime()>myPlant.getEndTime()){
                myPlant.setState(1);
                mongoTemplate.save(myPlant);
            }
        }
        
    }


    /**
     * 牧场动物状态修改
     */
    @Scheduled(fixedRate = 1000*5)
    public void PastureAnimalStatus(){
        List<Integer> val = new ArrayList<>();
        val.add(PastureGrowUpType.SHQ.getType());val.add(PastureGrowUpType.SCQ.getType());
        Query query = new Query().addCriteria(Criteria.where("type").nin(val));
        //获取非生产期，非收获期数据
        List<PastureFeeding> feedingList = mongoTemplate.find(query,PastureFeeding.class);
        for (PastureFeeding feeding:feedingList){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (System.currentTimeMillis()>feeding.getEndTime()){
                        //收获期
                        feeding.setType(PastureGrowUpType.SHQ.getType());
                        mongoTemplate.save(feeding);
                    }else if (System.currentTimeMillis()>feeding.getNextProduceTime()){
                        MyPasture myPasture = myPastureRepository.findByOpenId(feeding.getOpenId());
                        //幼崽期判断
                        if (feeding.getType()==PastureGrowUpType.YZQ.getType() ){
                            //更新至成长期
                            feeding.setType(PastureGrowUpType.CZQ.getType());
                            feeding.setTypeName(PastureGrowUpType.CZQ.getName());
                            feeding.setNestTypeName(PastureGrowUpType.SCQ.getName());
                            feeding.setNextProduceTime(feeding.getGrowthPeriodTime()+System.currentTimeMillis());
                            mongoTemplate.save(feeding);
                        }else if (feeding.getType()==PastureGrowUpType.CZQ.getType() && myPasture.getMucao()>0){
                            if (myPasture.getMucao()>0){
                                //更新至生产期
                                feeding.setType(PastureGrowUpType.SCQ.getType());
                                mongoTemplate.save(feeding);
                            }

                        }else if (feeding.getType()==PastureGrowUpType.DCQ.getType()&& myPasture.getMucao()>0){
                            if (myPasture.getMucao()>0){
                                //待产期更新至生产期
                                feeding.setType(PastureGrowUpType.SCQ.getType());
                                mongoTemplate.save(feeding);
                            }

                        }
                    }


                }
            }).start();
        }
    }


    /**
     * 牧草消耗
     */
    @Scheduled(fixedRate = 1000*60*60*4)
    public void mucao(){
        List<Integer> val = new ArrayList<>();
        List<MyPasture> myPastures =myPastureRepository.findAll();
        for (MyPasture myPasture:myPastures){
            Integer totalMc =0;
            //获取非生产期，非收获期数据
            Criteria criteria = new Criteria();
            criteria.and("openId").is(myPasture.getOpenId());
            Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                    Aggregation.group("openId").sum("mucao").as("totalMc"));
            AggregationResults<Map> results = mongoTemplate.aggregate(aggregation,PastureFeeding.class, Map.class);
            List<Map> mapList = results.getMappedResults();
            for (Map map : mapList) {
              totalMc= (Integer) map.get("totalMc");
            }
            if (myPasture.getMucao()-totalMc<0){
                myPasture.setMucao(0);
            }else {
                myPasture.setMucao(myPasture.getMucao()-totalMc);
            }
            mongoTemplate.save(myPasture);
        }

    }
}
